package com.example.petshopping.ui.profile;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.example.petshopping.R;
import com.example.petshopping.ui.main.MainActivity;
import com.example.petshopping.ui.category.CategoryActivity;
import com.example.petshopping.ui.message.MessageActivity;
import com.example.petshopping.ui.bidding.BiddingViewActivity;
import com.example.petshopping.ui.follows.FollowsActivity;
import com.example.petshopping.ui.orders.OrdersActivity;
import com.example.petshopping.utils.UserInfoManager;
import com.example.petshopping.model.AppMemberUserInfoRespVO;
import com.example.petshopping.model.CommonResult;
import com.example.petshopping.network.RetrofitClient;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProfileActivity extends AppCompatActivity {

    private static final String TAG = "ProfileActivity";
    private TextView tvNickname;
    private ImageView ivAvatar;
    private TextView tvFollows;
    private TextView tvFans;
    private TextView tvHistory;
    private View btnSettings;
    
    // 订单项的徽章
    private TextView tvPendingConfirmBadge;
    private TextView tvPendingPaymentBadge;
    private TextView tvPendingDeliveryBadge;
    private TextView tvPendingReceiptBadge;
    private TextView tvRefundBadge;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_profile);
            
            initViews();
            loadUserInfo();
            setupOrderSection();
            setupBottomNavigation();
        } catch (Exception e) {
            Log.e(TAG, "onCreate发生错误: ", e);
            Toast.makeText(this, "页面加载失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 每次页面恢复时重新加载用户信息，以确保显示最新数据
        loadUserInfo();
    }
    
    private void initViews() {
        // 用户信息区域
        tvNickname = findViewById(R.id.tv_nickname);
        ivAvatar = findViewById(R.id.iv_avatar);
        tvFollows = findViewById(R.id.tv_follows_count);
        tvFans = findViewById(R.id.tv_fans_count);
        tvHistory = findViewById(R.id.tv_history_count);
        btnSettings = findViewById(R.id.btn_settings);
        
        // 订单区域
        tvPendingConfirmBadge = findViewById(R.id.tv_pending_confirm_badge);
        tvPendingPaymentBadge = findViewById(R.id.tv_pending_payment_badge);
        tvPendingDeliveryBadge = findViewById(R.id.tv_pending_delivery_badge);
        tvPendingReceiptBadge = findViewById(R.id.tv_pending_receipt_badge);
        tvRefundBadge = findViewById(R.id.tv_refund_badge);
        
        // 设置页面点击事件
        btnSettings.setOnClickListener(v -> {
            Intent intent = new Intent(this, com.example.petshopping.ui.settings.SettingsActivity.class);
            startActivity(intent);
        });
        
        // 头像点击事件 - 跳转到个人信息页面
        ivAvatar.setOnClickListener(v -> {
            Intent intent = new Intent(this, UserInfoActivity.class);
            overridePendingTransition(0,0);
            startActivity(intent);
        });
        
        // 全部订单点击事件
        findViewById(R.id.tv_view_all_orders).setOnClickListener(v -> {
            navigateToOrders(0);
        });
        
        // 钱包卡片点击事件
        findViewById(R.id.card_wallet).setOnClickListener(v -> {
            Toast.makeText(this, "钱包功能即将上线", Toast.LENGTH_SHORT).show();
        });
        
        // 出价/围观卡片点击事件
        findViewById(R.id.card_bidding).setOnClickListener(v -> {
            // 跳转到出价/围观页面
            startActivity(new Intent(this, BiddingViewActivity.class));
        });
        
        // 开店按钮点击事件
        findViewById(R.id.btn_open_store).setOnClickListener(v -> {
            Toast.makeText(this, "开店功能即将上线", Toast.LENGTH_SHORT).show();
        });
        
        // 参与按钮点击事件
        findViewById(R.id.fab_participate).setOnClickListener(v -> {
            Toast.makeText(this, "参与功能即将上线", Toast.LENGTH_SHORT).show();
        });
        
        // 订单状态项点击事件 - 跳转到订单页面并指定标签
        findViewById(R.id.layout_pending_confirm).setOnClickListener(v -> {
            navigateToOrders(1); // 待确认标签
        });
        
        findViewById(R.id.layout_pending_payment).setOnClickListener(v -> {
            navigateToOrders(2); // 待付款标签
        });
        
        findViewById(R.id.layout_pending_delivery).setOnClickListener(v -> {
            navigateToOrders(3); // 待发货标签
        });
        
        findViewById(R.id.layout_pending_receipt).setOnClickListener(v -> {
            navigateToOrders(4); // 待收货标签
        });
        
        findViewById(R.id.layout_refund).setOnClickListener(v -> {
            navigateToOrders(5); // 退款/售后标签
        });
        
        // 添加整个订单卡片的点击事件 - 跳转到全部订单
        View cardOrders = findViewById(R.id.card_orders);
        if (cardOrders != null) {
            cardOrders.setOnClickListener(v -> {
                navigateToOrders(0); // 全部订单标签
            });
        }
    }
    
    // 封装导航到订单页面的方法，添加错误处理
    private void navigateToOrders(int defaultTab) {
        try {
            Intent intent = new Intent(this, OrdersActivity.class);
            intent.putExtra("default_tab", defaultTab);
            Log.d(TAG, "跳转到订单页面，标签: " + defaultTab);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "跳转到订单页面失败: ", e);
            Toast.makeText(this, "无法打开订单页面: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private void loadUserInfo() {
        // 首先从网络获取最新用户信息
        fetchUserInfoFromNetwork();
        
        // 同时加载本地缓存的信息作为初始显示
        loadLocalUserInfo();
        
        // 设置其他数据和点击事件
        setupUserInfoClickEvents();
    }
    
    /**
     * 获取用户信息
     */
    private void fetchUserInfoFromNetwork() {
        // 发送获取用户信息请求（Authorization头已由拦截器自动添加）
        RetrofitClient.getInstance().getApiService().getUserInfo()
                .enqueue(new Callback<CommonResult<AppMemberUserInfoRespVO>>() {
                    @Override
                    public void onResponse(Call<CommonResult<AppMemberUserInfoRespVO>> call, Response<CommonResult<AppMemberUserInfoRespVO>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            CommonResult<AppMemberUserInfoRespVO> result = response.body();
                            if (result.isSuccess() && result.getData() != null) {
                                // 获取用户信息成功，保存并更新UI
                                AppMemberUserInfoRespVO userInfo = result.getData();
                                UserInfoManager.saveUserInfo(ProfileActivity.this, userInfo);
                                
                                // 更新UI显示
                                updateUserInfoDisplay(userInfo);
                                
                                Log.d(TAG, "从网络获取用户信息成功");
                            } else {
                                Log.w(TAG, "获取用户信息失败: " + result.getMsg());
                            }
                        } else {
                            Log.w(TAG, "获取用户信息网络请求失败");
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<CommonResult<AppMemberUserInfoRespVO>> call, Throwable t) {
                        Log.e(TAG, "获取用户信息网络请求失败", t);
                        // 网络请求失败时，继续使用本地缓存的信息
                    }
                });
    }
    
    /**
     * 加载本地用户信息
     */
    private void loadLocalUserInfo() {
        // 从本地存储加载用户信息
        AppMemberUserInfoRespVO userInfo = UserInfoManager.getUserInfo(this);
        
        if (userInfo != null) {
            updateUserInfoDisplay(userInfo);
        } else {
            // 如果没有用户信息，使用默认值
            tvNickname.setText(UserInfoManager.getUserNickname(this));
            
            // 尝试加载保存的头像URL
            loadAvatar(UserInfoManager.getUserAvatar(this));
        }
    }
    
    /**
     * 更新用户信息显示
     */
    private void updateUserInfoDisplay(AppMemberUserInfoRespVO userInfo) {
        // 设置用户昵称
        if (userInfo.getNickname() != null && !userInfo.getNickname().isEmpty()) {
            tvNickname.setText(userInfo.getNickname());
        } else {
            tvNickname.setText("用户" + (userInfo.getId() != null ? userInfo.getId() : ""));
        }
        
        // 加载用户头像
        loadAvatar(userInfo.getAvatar());
    }
    
    /**
     * 设置用户信息相关的点击事件
     */
    private void setupUserInfoClickEvents() {
        // 模拟其他数据（关注、粉丝、浏览历史）
        tvFollows.setText("35");
        tvFans.setText("35");
        tvHistory.setText("42");
        
        // 添加关注/粉丝区域点击事件
        View followsSection = findViewById(R.id.layout_follows_stats);
        if (followsSection != null) {
            followsSection.setOnClickListener(v -> {
                // 跳转到关注/粉丝页面
                startActivity(new Intent(this, FollowsActivity.class));
            });
        }
        
        // 添加单独的关注和粉丝计数点击事件
        View followsCount = findViewById(R.id.tv_follows_count);
        if (followsCount != null) {
            followsCount.setOnClickListener(v -> {
                Intent intent = new Intent(this, FollowsActivity.class);
                intent.putExtra("default_tab", 1); // 打开"关注的店"标签
                startActivity(intent);
            });
        }
        
        View fansCount = findViewById(R.id.tv_fans_count);
        if (fansCount != null) {
            fansCount.setOnClickListener(v -> {
                Intent intent = new Intent(this, FollowsActivity.class);
                intent.putExtra("default_tab", 2); // 打开"我的粉丝"标签
                startActivity(intent);
            });
        }
    }
    
    private void setupOrderSection() {
        // 设置各个订单状态的徽章
        // 这里的数据后续应该从API获取，现在先设置示例数据
        setOrderBadge(tvPendingConfirmBadge, 3); // 待确认 3 个
        setOrderBadge(tvPendingPaymentBadge, 2); // 待付款 2 个
        setOrderBadge(tvPendingDeliveryBadge, 1); // 待发货 1 个
        setOrderBadge(tvPendingReceiptBadge, 4); // 待收货 4 个
        setOrderBadge(tvRefundBadge, 0); // 退款售后 0 个（不显示）
    }
    
    /**
     * 设置订单徽章显示
     * @param badge 徽章TextView
     * @param count 数量，0表示不显示徽章
     */
    private void setOrderBadge(TextView badge, int count) {
        if (badge != null) {
            if (count > 0) {
                badge.setText(String.valueOf(count));
                badge.setVisibility(View.VISIBLE);
            } else {
                badge.setVisibility(View.GONE);
            }
        }
    }
    
    /**
     * 更新所有订单徽章数据
     * 这个方法可以被外部调用来更新从API获取的最新数据
     * @param confirmCount 待确认数量
     * @param paymentCount 待付款数量
     * @param deliveryCount 待发货数量
     * @param receiptCount 待收货数量
     * @param refundCount 退款售后数量
     */
    public void updateOrderBadges(int confirmCount, int paymentCount, int deliveryCount, 
                                 int receiptCount, int refundCount) {
        setOrderBadge(tvPendingConfirmBadge, confirmCount);
        setOrderBadge(tvPendingPaymentBadge, paymentCount);
        setOrderBadge(tvPendingDeliveryBadge, deliveryCount);
        setOrderBadge(tvPendingReceiptBadge, receiptCount);
        setOrderBadge(tvRefundBadge, refundCount);
    }
    
    private void setupBottomNavigation() {
        BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
        
        // 设置当前选中项为"我的"
        bottomNav.setSelectedItemId(R.id.navigation_profile);
        
        // 设置点击监听器
        bottomNav.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    startActivity(new Intent(this, MainActivity.class));
                    // 禁用页面切换动画
                    overridePendingTransition(0, 0);
                    finish();
                    return true;
                case R.id.navigation_category:
                    startActivity(new Intent(this, CategoryActivity.class));
                    // 禁用页面切换动画
                    overridePendingTransition(0, 0);
                    finish();
                    return true;
                case R.id.navigation_message:
                    startActivity(new Intent(this, MessageActivity.class));
                    // 禁用页面切换动画
                    overridePendingTransition(0, 0);
                    finish();
                    return true;
                case R.id.navigation_profile:
                    // 当前已在我的页面
                    return true;
            }
            return false;
        });
        
        // 设置中间按钮点击事件
        FloatingActionButton centerButton = findViewById(R.id.center_button);
        centerButton.setOnClickListener(v -> {
            Toast.makeText(this, "此功能即将上线", Toast.LENGTH_SHORT).show();
        });
    }
    
    /**
     * 加载用户头像
     * @param avatarUrl 头像URL，可能为空
     */
    private void loadAvatar(String avatarUrl) {
        if (avatarUrl != null && !avatarUrl.isEmpty()) {
            // 使用Glide加载网络头像
            Glide.with(this)
                    .load(avatarUrl)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .placeholder(R.drawable.cat) // 加载中显示默认头像
                    .error(R.drawable.cat) // 加载失败显示默认头像
                    .into(ivAvatar);
        } else {
            // 如果没有头像URL，使用默认头像
            ivAvatar.setImageResource(R.drawable.cat);
        }
    }
} 